package com.zhongyouyun.utils;



import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析xml的工具类
 * 1、将多层级xml解析为Map
 */
public class ParseXmlUtil {
    public static final String TAG = "ParseXmlUtil";

    /**
     * 将xml格式响应报文解析为Map格式
     *
     * @param responseXmlTemp
     * @return
     * @throws DocumentException
     */
    public static Map<String, Object> xml2map(String responseXmlTemp) throws DocumentException {
        Document doc = DocumentHelper.parseText(responseXmlTemp);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new HashMap<>();
        element2Map(mapXml, rootElement);
        return mapXml;
    }

    /**
     * 使用递归调用将多层级xml转为map
     *
     * @param map
     * @param rootElement
     */
    private static void element2Map(Map<String, Object> map, Element rootElement) {
        // 获得当前节点的子节点
        List<Element> childElements = rootElement.elements();
       // Log.d(TAG, "element name :" + rootElement.getName() + " -- childElements size：" + childElements.size());
        if (childElements.size() > 0) {
            Map<String, Object> tempMap = new HashMap<>();
            for (Element e : childElements) {
                element2Map(tempMap, e);
                map.put(rootElement.getName(), tempMap);
            }
        } else {
            //Log.d(TAG, "当前无子节点 name :" + rootElement.getName() + ":" + rootElement.getText());
            map.put(rootElement.getName(), rootElement.getText());
        }
    }
}